--[[
refer: <<program in lua>> chapter 9

GET /TR/html401/html40.txt HTTP/1.1
host: www.w3c.org

--]]

local socket = require('socket')

host = "www.w3.org"
-- host = "localhost"
local port = 80
if host=='localhost' then port=8888 end

function get(host, file)
  local c = assert(socket.connect(host, port), "error at socket.connect()")
  local str = "GET "..file.." HTTP/1.1\r\nHost: " .. host .. "\r\n\r\n"
  -- print(str)

  local count=0
  c:send(str)

  while true do
    -- local s, status = c:receive(2^10) -- block io, size not right
    local s, status = c:receive('*a') -- block io
    -- print('status=', status)
    if s then
      count = count + #s
      -- print('count=',count)
    end

    if status == "closed" then break end
  end

  c:close()
  print(file,'count=' .. count)
end

function blockIO()
  local startAt = socket.gettime()
  local cpuTime1 = os.clock()
  
  get(host, "/TR/REC-html32.html")
  get(host, "/TR/html401/html40.txt")
  get(host,"/TR/2002/REC-xhtml1-20020801/xhtml1.pdf")
  get(host,"/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt")

  print("time elapse = ",socket.gettime() - startAt)
  print("cpu time elapse = ",os.clock() - cpuTime1)


end

blockIO()
-- time elapse =   28.581546783447
-- cpu time elapse =   0.088438